package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.utility.SnowflakeIdWorker;
import com.search.common.dto.client.ItemClient;
import com.search.common.dto.client.UserClient;
import com.search.common.dto.pojo.Address;
import com.search.common.dto.pojo.Item;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.pojo.OrderVO;
import com.hmall.order.service.IOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired(required=true)
    ItemClient itemClient;
    @Autowired
    UserClient userClient;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    OrderLogisticsMapper orderLogisticsMapper;
    @Override
    public void addOrder(OrderVO orderVO) {
        Order order = new Order();
        order.setStatus(1);
        Item item = itemClient.getById(orderVO.getItemId());
        order.setTotalFee((long)(orderVO.getNum()*item.getPrice()));
        BeanUtils.copyProperties(orderVO,order);
        Address address = userClient.findAddressById(orderVO.getAddressId());
        //将Order写入数据库tb_order表中
        order.setUserId(address.getUserId());
        try {
            order.setId(SnowflakeIdWorker.getKey());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        Long insert = (long)orderMapper.insert(order);

        OrderDetail orderDetail = new OrderDetail();
        BeanUtils.copyProperties(item,orderDetail);
        orderDetail.setOrderId(insert);
        //将商品信息、orderId信息封装为OrderDetail对象，写入tb_order_detail表
        orderDetailMapper.insert(orderDetail);
        //根据addressId查询user-service服务，获取地址信息

        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
        //将地址封装为OrderLogistics对象，写入tb_order_logistics表
        orderLogisticsMapper.insert(orderLogistics);
        //调用item-service的减库存接口
        itemClient.UpStock(orderVO.getItemId(),orderVO.getNum());
    }
}
